import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class HelloScriptingWorld {

    public static void main(String[] args) throws ScriptException, NoSuchMethodException {

        ScriptEngineManager scriptEngineMgr = new ScriptEngineManager();
        ScriptEngine jsEngine = scriptEngineMgr.getEngineByName("JavaScript");

        if (jsEngine == null) {
            System.err.println("No script engine found for JavaScript");
            System.exit(1);
        }

        System.out.println("Calling invokeHelloScript...");
        invokeHelloScript(jsEngine);

        System.out.println("\nCalling defineScriptFunction...");
        defineScriptFunction(jsEngine);

        System.out.println("\nCalling invokeScriptFunctionFromEngine...");
        invokeScriptFunctionFromEngine(jsEngine);

        System.out.println("\nCalling invokeScriptFunctionFromJava...");
        invokeScriptFunctionFromJava(jsEngine);

        System.out.println("\nCalling invokeJavaFromScriptFunction...");
        invokeJavaFromScriptFunction(jsEngine);
    }

    //调用脚本语言
    private static void invokeHelloScript(ScriptEngine jsEngine) throws ScriptException {
        jsEngine.eval("print('Hello from JavaScript')");
    }

    //定义脚本语言
    private static void defineScriptFunction(ScriptEngine engine) throws ScriptException {
        // Define a function in the script engine
        engine.eval("function sayHello(name) {" + "    print('Hello, ' + name)" + "}");
    }

    //调用脚本语言
    private static void invokeScriptFunctionFromEngine(ScriptEngine engine) throws ScriptException {
        engine.eval("sayHello('World!')");
    }

    //java调用脚本语言
    private static void invokeScriptFunctionFromJava(ScriptEngine engine)
            throws ScriptException, NoSuchMethodException {
        Invocable invocableEngine = (Invocable) engine;
        invocableEngine.invokeFunction("sayHello", "from Java");
    }

    //脚本语言中调用java方法
    private static void invokeJavaFromScriptFunction(ScriptEngine engine) throws ScriptException {
        engine.put("helloScriptingWorld", new HelloScriptingWorld());
        engine.eval("print('Invoking getHelloReply method from JavaScript...');"
                + "var msg = helloScriptingWorld.getHelloReply('vJavaScript');" + "print('Java returned:' + msg);");
    }

    /** Method invoked from the above script to return a string. */
    public String getHelloReply(String name) {
        return "Java method getHelloReply says, 'Hello, " + name + "'";
    }
}
